<template>
  <div class="system-user-dialog-container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="769px">
      <el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="90px" size="default">
        <el-row :gutter="35">
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="会员昵称" prop="nickName">
              <el-input v-model="state.ruleForm.nickName" :disabled="formReadonly" clearable
                        placeholder="请输入会员昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="state.ruleForm.phone" :disabled="formReadonly" clearable
                        placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="state.ruleForm.wechat" :disabled="formReadonly" clearable
                        placeholder="请输入微信"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="state.ruleForm.sex" :disabled="formReadonly" class="w100" clearable
                         placeholder="请选择">
                <el-option
                    v-for="item in state.sexList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="阳历生日" prop="solarBirthday">
              <el-date-picker v-model="state.ruleForm.solarBirthday" :disabled="formReadonly" class="w100"
                              placeholder="请选择"
                              type="date" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="客单价" prop="customerPrice">
              <el-input v-model="state.ruleForm.customerPrice" :disabled="formReadonly" clearable
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="负责顾问" prop="userId">
              <el-select v-model="state.ruleForm.userId" :disabled="formReadonly" class="w100" clearable
                         placeholder="请选择">
                <el-option
                    v-for="item in state.userList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="推荐人" prop="referrerId">
              <el-select v-model="state.ruleForm.referrerId" :disabled="formReadonly" class="w100" clearable
                         placeholder="请选择">
                <el-option
                    v-for="item in state.infoList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="会员来源" prop="registrationSource">
              <el-select v-model="state.ruleForm.registrationSource" :disabled="formReadonly" class="w100" clearable
                         placeholder="请选择">
                <el-option
                    v-for="item in state.sourceList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="会员等级" prop="memberGrade">
              <el-select v-model="state.ruleForm.memberGrade" :disabled="formReadonly" class="w100"
                         placeholder="请选择">
                <el-option
                    v-for="item in state.gradeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="标签" prop="labelIdList">
              <el-select v-model="state.ruleForm.labelIdList"
                         :disabled="formReadonly"
                         class="w100"
                         clearable multiple
                         placeholder="请选择">
                <el-option
                    v-for="item in state.labelList"
                    :key="item.id"
                    :label="item.labelName"
                    :value="item.id+''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="state.ruleForm.remark" :disabled="formReadonly" maxlength="150"
                        placeholder="请输入备注"
                        type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="primary" @click="onSubmit(userDialogFormRef)">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="systemUserDialog" setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import {memberInfoApi} from "/@/api/member/info";
import {dictDataApi} from "/@/api/sys/dictData";
import {memberLabelApi} from "/@/api/member/label";
import {userApi} from "/@/api/sys/user";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    nickName: '', // 会员昵称
    phone: '', // 手机号码
    wechat: '', // 微信
    sex: '', // 性别
    registrationSource: '', //来源
    memberGrade: '', //会员等级
    solarBirthday: '', // 阳历生日
    userId: '', // 员工ID(负责人)
    customerPrice: '', // 客单价
    labelIdList: [], // 标签List
    remark: '', // 备注
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  sexList: [],
  sourceList: [],
  gradeList: [],
  labelList: [],
  infoList: [],
  userList: [],
});
const rules = reactive<FormRules>({
  phone: [{required: true, message: '不能为空', trigger: 'blur'}],
  nickName: [{required: true, message: '不能为空', trigger: 'blur'}],
  registrationSource: [{required: true, message: '不能为空', trigger: 'blur'}],
  solarBirthday: [{required: true, message: '不能为空', trigger: 'blur'}],
  sex: [{required: true, message: '不能为空', trigger: 'change'}],
});
// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  if (type === 'edit') {
    state.dialog.title = '修改用户';
    state.dialog.submitTxt = '修 改';
    memberInfoApi()
        .getInfo(row.id)
        .then(res => {
          state.ruleForm.labelIdList = res.data.labelIds.split(',');
        })
  } else if (type === 'add') {
    state.dialog.title = '新增用户';
    state.dialog.submitTxt = '新 增';
  }
  nextTick(() => {
    if (type === 'add') {
      // 清空表单，此项需加表单验证才能使用
      userDialogFormRef.value.resetFields();
    } else {
      state.ruleForm = Object.assign(state.ruleForm, row);
    }
  });
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (state.dialog.type === 'add') {
        memberInfoApi()
            .addRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '新增成功');
                closeDialog();
                emit('refresh');
              }
            });
      } else if (state.dialog.type === 'edit') {
        memberInfoApi()
            .updateRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '修改成功');
                closeDialog();
                emit('refresh');
              }
            });
      }
    }
  });
};

// 页面加载时
onMounted(() => {
  // 性别
  dictDataApi()
      .getDictByType('sys_user_sex')
      .then(res => {
        state.sexList = res.data;
      })
  // 来源
  dictDataApi()
      .getDictByType('member_source')
      .then(res => {
        state.sourceList = res.data;
      })
  // 会员等级
  dictDataApi()
      .getDictByType('member_grade')
      .then(res => {
        state.gradeList = res.data;
      })
  // 获取标签信息
  memberLabelApi()
      .findAll()
      .then(res => {
        state.labelList = res.data;
      })
  // 获取人员信息
  memberInfoApi()
      .findAll()
      .then(res => {
        state.infoList = res.data;
      })
  // 用户数据
  userApi()
      .findAll()
      .then(res => {
        state.userList = res.data;
      })
});

const formReadonly = computed(() => {
  return state.dialog.type !== 'add' && state.dialog.type !== 'edit'
})
// 暴露变量
defineExpose({
  openDialog,
});
</script>
